package com.example.boot1.service.impl;

import com.example.boot1.bean.Image;
import com.example.boot1.service.UploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class UploadServiceImpl implements UploadService {

    private  final static String rootPath = "D:/java-space/workspace2023own/project-study/boot1-springmvc/src/main/resources/static/tempimg/";

    @Override
    public List<Image> upload(MultipartFile[] multipartFiles) {
        File fileDir = new File(rootPath);
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        List<Image> list = new ArrayList<>();
        try {
            if (multipartFiles != null && multipartFiles.length > 0) {
                for(int i = 0;i<multipartFiles.length;i++){
                    String fileSuffix = getFileExtension(multipartFiles[i].getOriginalFilename());

                    try {
                        System.out.println("查看保存名称："+multipartFiles[i].getOriginalFilename());
                        String fileName = UUID.randomUUID().toString();
                        //String storagePath = rootPath+fileName+getFileExtension(multipartFiles[i].getOriginalFilename());
                        //String serverPath = "http://127.0.0.1:8083/image/"+fileName+getFileExtension(multipartFiles[i].getOriginalFilename());

                        String storagePath = rootPath+multipartFiles[i].getOriginalFilename();
                        String serverPath = "http://127.0.0.1:8083/image/"+multipartFiles[i].getOriginalFilename();

                        System.out.println("上传的文件：" + multipartFiles[i].getName() + "," +
                                multipartFiles[i].getContentType() + "," + multipartFiles[i].getOriginalFilename()
                                +"，保存的路径为：" + storagePath+i);
                        Path path = Paths.get(storagePath);
                        Files.write(path,multipartFiles[i].getBytes());

                        Image image = new Image(multipartFiles[i].getOriginalFilename(),storagePath,serverPath);
                        list.add(image);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //向前端返回一个图片列表
        return list;
    }
    private String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex >= 0 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex);
        }
        return "";
    }
}
